/* eslint-disable indent */
/* eslint-disable @typescript-eslint/indent */
import React from 'react';

import { Tooltip, Popover, Modal, Icon, Typography, Tag, Checkbox } from 'antd';
import LinkTo from '@/components/LinkTo';
import { history } from 'umi'
import Employee from '@/pages/Organization/OrgFlow/components/employee';
import cn from 'classnames';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import authHelper from '@/utils/auth/helper';
import { toArray } from '@/utils/utils';
import { eventTrack } from '@/utils/track';
import IconFont from '@/components/IconFont';
import { isSupervisorApprovaling } from '@/pages/Organization/OrgFlow/utils';
import styles from './index.less';
import { changeDepartmentToHistory, changeCompanyToHistory, orgDeleteCheck } from '../services';

const { confirm } = Modal;
const { checkCode } = authHelper;
const organizationTypeDict = ['', '集团', '公司', '部门'];

const renderEllipsis = text => (
    <div style={{ width: '100%', minWidth: 200, position: 'relative' }}>
        <span
            style={{
                position: 'absolute',
                left: 0,
                right: 0,
                top: 0,
                transform: 'translateY(-50%)',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis'
            }}
            title={text}
        >
            {text}
        </span>
    </div>
);
const getOperation = (text, record) => {
    const isSuperApprovaling = isSupervisorApprovaling(record);

    return (
        <React.Fragment>
            {checkCode('office:orgs:organization:new') && (
                <>
                    <Tooltip title="新增公司">
                        <i
                            disabled={record.organizationType === 3 || record.auditStatus !== 2}
                            className={cn('iconfont iconlistfunction_addcompany_icon_default', styles.icon)}
                            onClick={async () => {
                                if (record.organizationType === 2) {
                                    // 公司
                                    await eventTrack({
                                        eventName: 'personnel_management_organization_company_manage_operator_click',
                                        pageName: 'personnel_management_organization',
                                        eventProps: {
                                            click_context: `${record.organizationName}-新增公司`
                                        }
                                    });
                                } else if (record.organizationType === 3) {
                                    // 部门
                                    await eventTrack({
                                        eventName: 'personnel_management_organization_department_manage_operator_click',
                                        pageName: 'personnel_management_organization',
                                        eventProps: {
                                            click_context: `${record.organizationName}-新增公司`
                                        }
                                    });
                                }

                                history.push({
                                    pathname: '/office/personnelManagement/organization/companyadd',
                                    query: {
                                        organizationCode: record.organizationCode,
                                        organizationPath: record.organizationPath,
                                        organizationName: record.organizationName
                                    }
                                });
                            }}
                        />
                    </Tooltip>
                    <Tooltip title="新增部门">
                        <i
                            disabled={record.organizationType === 2 || record.auditStatus !== 2}
                            className={cn('iconfont iconlistfunction_adddepartment_icon_default', styles.icon)}
                            onClick={async () => {
                                if (record.organizationType === 2) {
                                    // 公司
                                    await eventTrack({
                                        eventName: 'personnel_management_organization_company_manage_operator_click',
                                        pageName: 'personnel_management_organization',
                                        eventProps: {
                                            click_context: `${record.organizationName}-新增部门`
                                        }
                                    });
                                } else if (record.organizationType === 3) {
                                    // 部门
                                    await eventTrack({
                                        eventName: 'personnel_management_organization_department_manage_operator_click',
                                        pageName: 'personnel_management_organization',
                                        eventProps: {
                                            click_context: `${record.organizationName}-新增部门`
                                        }
                                    });
                                }

                                history.push({
                                    pathname: '/office/personnelManagement/organization/departmentadd',
                                    query: {
                                        organizationCode: record.organizationCode,
                                        organizationPath: record.organizationPath,
                                        organizationName: record.organizationName
                                    }
                                });
                            }}
                        />
                    </Tooltip>
                </>
            )}

            {checkCode('office:orgs:organization:duty:new') && (
                <Tooltip title="新增岗位">
                    <i
                        disabled={
                            record.organizationType === 1 || record.organizationType === 2 || record.auditStatus !== 2
                        }
                        className={cn('iconfont iconlistfunction_addpost_icon_default', styles.icon)}
                        onClick={async () => {
                            if (record.organizationType === 2) {
                                // 公司
                                await eventTrack({
                                    eventName: 'personnel_management_organization_company_manage_operator_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-新增岗位`
                                    }
                                });
                            } else if (record.organizationType === 3) {
                                // 部门
                                await eventTrack({
                                    eventName: 'personnel_management_organization_department_manage_operator_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-新增岗位`
                                    }
                                });
                            }

                            history.push({
                                pathname: '/office/personnelManagement/organization/postadd',
                                query: {
                                    organizationCode: record.organizationCode,
                                    organizationPath: record.organizationPath,
                                    organizationName: record.organizationName
                                }
                            });
                        }}
                    />
                </Tooltip>
            )}

            {checkCode('office:orgs:organization:edit') && (
                <Tooltip title="编辑">
                    <i
                        disabled={record.auditStatus !== 2 || isSuperApprovaling}
                        className={cn('iconfont iconlistfunction_edit_icon_default', styles.icon)}
                        onClick={async () => {
                            if (record.organizationType === 2) {
                                // 公司
                                await eventTrack({
                                    eventName: 'personnel_management_organization_company_manage_operator_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-编辑`
                                    }
                                });
                            } else if (record.organizationType === 3) {
                                // 部门
                                await eventTrack({
                                    eventName: 'personnel_management_organization_department_manage_operator_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-编辑`
                                    }
                                });
                            }

                            if (record.organizationType === 3) {
                                history.push({
                                    pathname: '/office/personnelManagement/organization/departmentedit',
                                    query: {
                                        organizationCode: record.organizationCode,
                                        organizationPath: record.organizationPath,
                                        organizationName: record.organizationName
                                    }
                                });
                            } else {
                                history.push({
                                    pathname: '/office/personnelManagement/organization/companyedit',
                                    query: {
                                        organizationCode: record.organizationCode,
                                        organizationPath: record.organizationPath,
                                        organizationName: record.organizationName
                                    }
                                });
                            }
                        }}
                    />
                </Tooltip>
            )}

            {checkCode('office:orgs:organization:delete') && (
                <Tooltip title="删除">
                    <i
                        disabled={record.auditStatus !== 2 || isSuperApprovaling}
                        className={cn('iconfont iconlistfunction_delete_icon_default', styles.icon, styles.delect)}
                        onClick={async () => {
                            if (record.organizationType === 2) {
                                // 公司
                                await eventTrack({
                                    eventName: 'personnel_management_organization_company_manage_operator_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-删除`
                                    }
                                });
                            } else if (record.organizationType === 3) {
                                // 部门
                                await eventTrack({
                                    eventName: 'personnel_management_organization_department_manage_operator_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-删除`
                                    }
                                });
                            }

                            const { organizationType, organizationCode } = record;
                            const confirmModal = confirm({
                                title: '确定删除？',
                                icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                                okText: '确认',
                                cancelText: '取消',
                                okButtonProps: {
                                    disabled: organizationType === 3
                                },
                                content: (
                                    <>
                                        {organizationType === 3 ? (
                                            <div className={styles.deleteInfo}>
                                                <p>删除此机构前请先确认：</p>
                                                <p>· 此机构下是否有在职员工？</p>
                                                <p>· 此机构下是否有岗位正在招聘？</p>
                                                <p>· 此机构下是否有正在入职的员工？</p>
                                                <p>上述情况皆无，才能够删除此机构</p>
                                                <div>
                                                    <Checkbox
                                                        onChange={e => {
                                                            confirmModal.update({
                                                                okButtonProps: {
                                                                    disabled: !e.target.checked
                                                                }
                                                            });
                                                        }}
                                                    >
                                                        确认删除此机构
                                                    </Checkbox>
                                                </div>
                                            </div>
                                        ) : (
                                            `删除${organizationTypeDict[organizationType]}将无法恢复，确定删除吗？`
                                        )}
                                    </>
                                ),
                                onOk: async () => {
                                    // 删除前校验
                                    const { msg, code: delCheckCode } = await orgDeleteCheck({ organizationCode });
                                    if (delCheckCode === 10000) {
                                        // 流程不存在提示
                                        const {
                                            workFlowPathname,
                                            workFlowQuery,
                                            workFlowErrorMsg
                                        } = await hasWorkFlowByType('organizationApply', false);
                                        if (!workFlowPathname) {
                                            Modal.error({
                                                title: '删除失败',
                                                icon: (
                                                    <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />
                                                ),
                                                content: workFlowErrorMsg,
                                                okText: '我知道了'
                                            });
                                            return;
                                        }

                                        const params = {
                                            organizationType,
                                            organizationCode,
                                            operationType: 2
                                        };
                                        const { code, data: id } = await (organizationType === 3
                                            ? changeDepartmentToHistory(params)
                                            : changeCompanyToHistory(params));

                                        if (code === 10000) {
                                            history.push({
                                                pathname: workFlowPathname,
                                                query: { ...workFlowQuery, hiDataId: id },
                                                state: { tabRoute: true, tabRefresh: true }
                                            });
                                        }
                                    } else {
                                        Modal.error({
                                            title: '删除失败',
                                            icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                                            content: msg,
                                            okText: '我知道了'
                                        });
                                    }
                                }
                            });
                        }}
                    />
                </Tooltip>
            )}
        </React.Fragment>
    );
};

// 公司
export const companyColumns = [
    {
        title: '公司',
        dataIndex: 'organizationName',
        render: (text, record) => (
            <Typography.Text style={{ marginBottom: 0, maxWidth: 300 }} title={text} ellipsis>
                <a
                    onClick={async e => {
                        e.stopPropagation();
                        await eventTrack({
                            eventName: 'personnel_management_organization_company_manage_info_click',
                            pageName: 'personnel_management_organization',
                            eventProps: {
                                click_context: text
                            }
                        });
                        history.push({
                            pathname: `/office/personnelManagement/organization/${
                                record.organizationType === 3 ? 'departmentinfo' : 'companyinfo'
                            }`,
                            query: {
                                organizationCode: record.organizationCode,
                                organizationPath: record.organizationPath,
                                organizationName: record.organizationName
                            }
                        });
                    }}
                >
                    {text}
                </a>
            </Typography.Text>
        )
    },
    /* {
        title: (
            <div>
                部门 (直属/下属)
            </div>
        ),
        dataIndex: 'departmentCounts',
        render: (text, record) => {
            const { directDepartmentNum = 0, underDepartmentNumber = 0 } = record;
            return record.organizationType === 2 ? (
                <span>- / -</span>
            ) : (
                <span>
                    <LinkTo
                        to="/office/personnelManagement/organization/departmentManage"
                        query={{
                            organizationPermissions: record.organizationPermissions,
                            organizationPath: record.organizationPath,
                            organizationType: 3,
                            organizationCode: record.organizationCode,
                            organizationName: record.organizationName,
                            auditStatus: record.auditStatus,
                            num: directDepartmentNum
                        }}
                    >
                        {directDepartmentNum}
                    </LinkTo>
                    &nbsp;/&nbsp;
                    <LinkTo
                        to="/office/personnelManagement/organization/subordinateManage"
                        query={{
                            organizationPermissions: record.organizationPermissions,
                            organizationPath: record.organizationPath,
                            organizationCode: record.organizationCode,
                            organizationName: record.organizationName,
                            auditStatus: record.auditStatus,
                            organizationType: 3,
                            num: underDepartmentNumber
                        }}
                    >
                        {underDepartmentNumber}
                    </LinkTo>
                </span>
            );
        }
    },
    {
        title: (
            <div>
                岗位<span style={{ fontSize: 12 }}>(编制/在职)</span>
            </div>
        ),
        dataIndex: 'employeeNum',
        render: (text, record) => {
            const { employeeNum = 0, planNum = 0 } = record;
            return record.organizationType === 2 ? (
                <span>- / -</span>
            ) : (
                <span>
                    <LinkTo
                        to="/office/personnelManagement/organization/postList"
                        query={{
                            organizationPermissions: record.organizationPermissions,
                            organizationPath: record.organizationPath,
                            organizationCode: record.organizationCode,
                            organizationName: record.organizationName,
                            auditStatus: record.auditStatus,
                            num: planNum
                        }}
                    >
                        {planNum}
                    </LinkTo>
                    &nbsp;/&nbsp;
                    <LinkTo
                        to="/office/personnelManagement/organization/employeeList"
                        query={{
                            // organizationPath: record.organizationPath || '',
                            organizationCodes: toArray(record.organizationCode)
                            // serviceStatus: [1, 2, 4, 5, 7]
                        }}
                    >
                        {employeeNum}
                    </LinkTo>
                </span>
            );
        }
    },
    {
        title: '主管',
        dataIndex: 'orgLeaders',
        render: (text, record) =>
            record.orgLeaders.map(employee => {
                const { employeeName, employeeCode } = employee;
                return (
                    <Popover
                        key={employeeCode}
                        content={
                            <Employee
                                employeeCode={employee.employeeCode}
                                organizationCode={employee.organizationCode}
                                organizationType={record.organizationType}
                            />
                        }
                        placement="bottomLeft"
                    >
                        <span className={styles.leaderName}>
                            {employeeName}
                            {employee.dutyType === 0 ? <Tag style={{ marginLeft: 4 }}>兼任</Tag> : null}
                        </span>
                    </Popover>
                );
            })
    }, */
    {
        title: '操作',
        dataIndex: 'operation',
        width: 200,
        render: (text, record) => (record.organizationPermissions ? getOperation(text, record) : null)
    }
];
// 直属部门
export const departmentColumns = [
    {
        title: '部门',
        dataIndex: 'organizationName',
        render: (text, record) => (
            <Typography.Text style={{ marginBottom: 0, maxWidth: 300 }} title={text} ellipsis>
                <a
                    onClick={async e => {
                        e.stopPropagation();
                        await eventTrack({
                            eventName: 'personnel_management_organization_department_manage_info_click',
                            pageName: 'personnel_management_organization',
                            eventProps: {
                                click_context: text
                            }
                        });
                        history.push({
                            pathname: `/office/personnelManagement/organization/${
                                record.organizationType === 3 ? 'departmentinfo' : 'companyinfo'
                            }`,
                            query: {
                                organizationCode: record.organizationCode,
                                organizationPath: record.organizationPath,
                                organizationName: record.organizationName
                            }
                        });
                    }}
                >
                    {text}
                </a>
            </Typography.Text>
        )
    },
    {
        title: (
            <div>
                岗位<span style={{ fontSize: 12 }}>(编制/在职)</span>
            </div>
        ),
        dataIndex: 'employeeNum',
        render: (text, record) => {
            const { employeeNum = 0, planNum = 0 } = record;
            return (
                <span>
                    <a
                        onClick={async e => {
                            e.stopPropagation();
                            await eventTrack({
                                eventName:
                                    'personnel_management_organization_department_manage_post_establishment_num_click',
                                pageName: 'personnel_management_organization',
                                eventProps: {
                                    click_context: `${record.organizationName}-编制人数-${planNum}`
                                }
                            });

                            history.push({
                                pathname: '/office/personnelManagement/organization/postList',
                                query: {
                                    organizationPermissions: record.organizationPermissions,
                                    organizationPath: record.organizationPath,
                                    organizationCode: record.organizationCode,
                                    organizationName: record.organizationName,
                                    auditStatus: record.auditStatus,
                                    num: planNum
                                }
                            });
                        }}
                    >
                        {planNum}
                    </a>
                    &nbsp;/&nbsp;
                    <a
                        onClick={async e => {
                            e.stopPropagation();
                            await eventTrack({
                                eventName:
                                    'personnel_management_organization_department_manage_post_incumbency_num_click',
                                pageName: 'personnel_management_organization',
                                eventProps: {
                                    click_context: `${record.organizationName}-在职人数-${employeeNum}`
                                }
                            });

                            history.push({
                                pathname: '/office/personnelManagement/organization/employeeList',
                                query: {
                                    organizationCodes: toArray(record.organizationCode)
                                }
                            });
                        }}
                    >
                        {employeeNum}
                    </a>
                </span>
            );
        }
    },
    {
        title: '主管',
        dataIndex: 'orgLeaders',
        render: (text, record) =>
            record.orgLeaders.map(employee => {
                const { employeeName, employeeCode } = employee;
                return (
                    <Popover
                        key={employeeCode}
                        content={
                            <Employee
                                employeeCode={employee.employeeCode}
                                organizationCode={employee.organizationCode}
                                organizationType={record.organizationType}
                            />
                        }
                        placement="bottomLeft"
                        onVisibleChange={async v => {
                            if (v) {
                                await eventTrack({
                                    eventName: 'personnel_management_organization_department_manage_leader_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-${employeeName}`
                                    }
                                });
                            }
                        }}
                    >
                        <span className={styles.leaderName}>
                            {employeeName}
                            {employee.dutyType === 0 ? (
                                <Tag style={{ marginLeft: 4 }} color="blue">
                                    兼任
                                </Tag>
                            ) : null}
                        </span>
                    </Popover>
                );
            })
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: 200,
        render: (text, record) => (record.organizationPermissions ? getOperation(text, record) : null)
    }
];
// 下属部门
export const subordinateColumns = [];

// 岗位管理
export const getPostColumns = () => [
    {
        title: '名称',
        dataIndex: 'dutyAlias',
        // width: 250,
        className: styles.organizationName,
        // eslint-disable-next-line no-confusing-arrow
        render: (text, record) => (
            <a
                // disabled={record.auditStatus === 1}
                className={styles.title}
                onClick={async e => {
                    e.stopPropagation();
                    await eventTrack({
                        eventName: 'personnel_management_organization_post_list_info_click',
                        pageName: 'personnel_management_organization',
                        eventProps: {
                            click_context: text
                        }
                    });
                    history.push({
                        pathname: '/office/personnelManagement/organization/postdetail',
                        query: {
                            organizationPermissions: record.organizationPermissions,
                            dutyCode: record.dutyCode,
                            organizationCode: record.organizationCode,
                            organizationPath: record.organizationPath,
                            organizationName: record.organizationName
                        },
                        state: { tabRoute: true, tabRefresh: true }
                    });
                }}
            >
                <Typography.Text
                    style={{ marginBottom: 0, maxWidth: 300, verticalAlign: 'bottom' }}
                    title={text}
                    ellipsis
                >
                    {text}
                    {record.leaderPositionFlag === 1 && record.leaderShowStatus !== 1 && (
                        <IconFont icon="iconLeaderMark" className={styles.employeeLeaderIcon} />
                    )}
                </Typography.Text>
            </a>
        )
    },
    {
        title: '审批状态',
        dataIndex: 'auditStatus',
        render: text => {
            const auditStatus = ['未审批', '审批中', '审批通过', '审批驳回'];
            return <span style={Number(text) === 1 ? { color: '#FFA22D' } : {}}>{auditStatus[text]}</span>;
        }
    },
    {
        title: (
            <div>
                岗位<span style={{ fontSize: 12 }}>(编制/在职)</span>
            </div>
        ),
        dataIndex: 'employeeNum',
        render: (text, record) => {
            const { planNum = 0, employeeNum = 0 } = record;
            return (
                <span>
                    {planNum}
                    &nbsp;/&nbsp;
                    <LinkTo
                        to="/office/personnelManagement/organization/employeeList"
                        query={{
                            organizationCodes: record.organizationCode,
                            dutyCodes: toArray(record.dutyCode)
                            // organizationType: record.organizationType || '',
                            // isOnlyCurrentLevel: 0, // 有 isOnlyCurrentLevel 就一定要带 organizationType 参数
                            // serviceStatus: [1, 2, 4, 5, 7]
                        }}
                    >
                        {employeeNum}
                    </LinkTo>
                </span>
            );
        }
    },
    {
        title: '层级',
        dataIndex: 'levelName',
        // width: '20%',
        render: text => renderEllipsis(text)
    },
    {
        title: '简介',
        dataIndex: 'dutyDesc',
        render: text => renderEllipsis(text)
    },
    {
        title: '状态',
        dataIndex: 'status',
        render: text => (text === 1 ? '启用' : '禁用')
    }
];
